/*
 * @Descripttion: 
 * @version: 
 * @Author: turingchang
 * @Date: 2020-08-25 09:23:14
 * @LastEditors: turingchang
 * @LastEditTime: 2020-09-08 17:10:36
 */
const validator =require('./validator');

var array = {};

/**
 * 数组去重
 * @param {Array} arr 
 */
array.deduplication = (arr) => {
  let n = {};
  let r = [];
  for (var i = 0; i < arr.length; i++) {
    if (!n[arr[i]]) {
      n[arr[i]] = true;
      r.push(arr[i]);
    }
  }
  return r;
}

/**
 * 数组根据某字段排序
 * @param {*} key       字段名
 * @param {*} sortType  排序方式，true为降序；false为升序
 * 使用方式：
 * var ary=[{id:1,name:"b"},{id:2,name:"b"}];
 * ary.sort(keysrt('id',false));
 */
array.keysort = (key, sortType = true) => {
  return function (a, b) {
    return sortType ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
  }
}

/**
 * 两个数组取出不同的值
 * @param {*} arr1 
 * @param {*} arr2 
 */
array.getArrDifference = (arr1, arr2) => {
  if(validator.isNull(arr1)){
    return arr2
  }
  if(validator.isNull(arr2)){
    return arr1
  }
  return arr1.concat(arr2).filter(function (v, i, arr) {
    return arr.indexOf(v) === arr.lastIndexOf(v);
  });
}

/**
 * 两个数组取出相同的值
 * @param {*} arr1 
 * @param {*} arr2 
 */
array.getArrEqual = (arr1, arr2) => {
  let newArr = [];
  if(validator.isNull(arr1)){
    return arr2
  }
  if(validator.isNull(arr2)){
    return arr
  }
  for (let i = 0; i < arr2.length; i++) {
    for (let j = 0; j < arr1.length; j++) {
      if (arr1[j] === arr2[i]) {
        newArr.push(arr1[j]);
      }
    }
  }
  return newArr;
}




module.exports = array;